package com.baozun.houji.me.viewmodel

import androidx.lifecycle.MutableLiveData
import com.baozhun.mall.common.util.onkeylogin.OneKeyLoginHelper
import com.baozhun.mall.common.widget.dialog.CommonDialog
import com.baozun.houji.me.R
import com.baozun.houji.me.model.request.PhoneLoginReqBean
import com.baozun.houji.me.network.mMeApiService
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request

/**
 * @Title：
 * @Description：
 * @Author：xing.luo
 * @Since：2022/12/9
 * @Version：1.0.0
 */
class RegisterViewModel : BaseViewModel() {
    var name = MutableLiveData("")
    var email = MutableLiveData("")
    var pwd = MutableLiveData("")
    var confirmPwd = MutableLiveData("")
    var verifyCode = MutableLiveData("")
    var agreeProtocol = MutableLiveData<Boolean>(true)


    /**
     * 注册
     */
    fun register(registerSuccess: () -> Unit) {
        checkParams {
            checkProtocol {
                request(
                    { mMeApiService.register(PhoneLoginReqBean(name.value, email.value, pwd.value)) },
                    {
                        registerSuccess.invoke()
                    },
                    isShowDialog = true,
                    showSuccessMsg = false
                )
            }
        }
    }

    private fun checkParams(checkPass: () -> Unit) {
        if (name.value.isNullOrEmpty()) {
            ToastUtils.showShort(com.baozhun.mall.res.R.string.please_input_name)
            return
        }
        if (email.value.isNullOrEmpty()) {
            ToastUtils.showShort(com.baozhun.mall.res.R.string.please_input_email)
            return
        }
        if (pwd.value.isNullOrEmpty()) {
            ToastUtils.showShort(com.baozhun.mall.res.R.string.please_input_pwd)
            return
        }
        if (!pwd.value.equals(confirmPwd.value)) {
            ToastUtils.showShort(com.baozhun.mall.res.R.string.two_passwords_are_different)
            return
        }
        checkPass.invoke()
    }

    /**
     * 检测协议是否选中
     */
    private fun checkProtocol(checkPass: () -> Unit) {
        if (agreeProtocol.value == true) {
            checkPass.invoke()
        } else {
            CommonDialog(ActivityUtils.getTopActivity()) {
                agreeProtocol.value = true
                checkPass.invoke()
            }.title(com.baozhun.mall.res.R.string.warm_reminder)
                .content(OneKeyLoginHelper.getInstance().getProtocolSpannableString("请先阅读并同意履行"))
                .cancelText(com.baozhun.mall.res.R.string.close)
                .confirmText(com.baozhun.mall.res.R.string.read_and_agree)
                .isClickableSpan(true)
                .dismissOnTouchOutside(false)
                .show()
        }

    }

}